package com.liu.frame.utils;

import android.text.TextUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串操作工具包
 */
public class StringUtils {
    private final static Pattern emailer = Pattern
            .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
    private final static SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private final static SimpleDateFormat dateFormater2 = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 将字符串转位日期类型
     *
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 以友好的方式显示时间
     *
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = toDate(sdate);
        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.format(cal.getTime());
        String paramDate = dateFormater2.format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max((cal.getTimeInMillis() - time.getTime()) / 60000, 1) + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.format(time);
        }
        return ftime;
    }

    /**
     * 判断给定字符串时间是否为今日
     *
     * @param sdate
     * @return boolean
     */
    public static boolean isToday(String sdate) {
        boolean b = false;
        Date time = toDate(sdate);
        Date today = new Date();
        if (time != null) {
            String nowDate = dateFormater2.format(today);
            String timeDate = dateFormater2.format(time);
            if (nowDate.equals(timeDate)) {
                b = true;
            }
        }
        return b;
    }

    /**
     * 判断给定字符串是否空白串。 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input) || input.length() == 0)
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 将字符串隐藏加星
     *
     * @param nickname
     * @return
     */
    public static String replaceStar(String nickname) {
        if (TextUtils.isEmpty(nickname)) {
            return "";
        }
        Pattern p_str = Pattern.compile("[\\u4e00-\\u9fa5]+");
        Matcher m = p_str.matcher(nickname);

        if (m.find() && m.group(0).equals(nickname)) {
            return nickname.substring(0, 1) + "***";
        } else {
            if (nickname.length() == 1) {
                return nickname.substring(0) + "***";
            } else if (nickname.length() == 2) {
                return nickname.substring(0, 1) + "***";
            } else if (nickname.length() >= 3) {
                return nickname.substring(0, 2) + "***";
            } else {
                return nickname;
            }
        }
    }

    /**
     * 判断给定字符串是否是可适用的数据，不可用返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isDataDisable(String input) {
        return TextUtils.isEmpty(input) || "null".equals(input);
    }

    public static boolean ispassword(String input) {
        if (input == null || "".equals(input))
            return false;
        Pattern p = Pattern.compile("[a-z_A-Z\\d]{6,}");
        Matcher m = p.matcher(input);
        return m.find();
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return emailer.matcher(email).matches();
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转float
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static float toFloat(Object obj) {
        if (obj == null)
            return 0;
        return toFloat(obj.toString());
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @return
     */
    public static float toFloat(String str) {
        try {
            return Float.parseFloat(str);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 对象转double
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static Double toDouble(Object obj) {
        if (obj == null)
            return 0.00;
        return toDouble(obj.toString());
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @return
     */
    public static Double toDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
        }
        return 0.00;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 字符串转布尔值
     *
     * @param b
     * @return 转换异常返回 false
     */
    public static boolean toBool(String b) {
        try {
            return Boolean.parseBoolean(b);
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 截取评定结果时间的日期
     *
     * @param date
     */
    public static String getDate(String date) {
        try {
            String[] dates = date.split(" ");
            if (dates != null && dates.length > 0) {
                return dates[0];
            } else
                return date;
        } catch (Exception e) {
            return date;
        }
    }

    /**
     * 将map的key 和 value 拼接成字符串
     *
     * @description: @param map
     * @description: @return
     * @author: caixuemei
     * @date: 2015-10-29 下午3:15:15
     */
    public static String splicingMap(Map<String, Object> map) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String key : map.keySet()) {
            stringBuffer.append(key + map.get(key));
        }
        return stringBuffer.toString();
    }

    /**
     * 中文参数转码
     *
     * @description: @param str
     * @description: @return
     * @author: caixuemei
     * @date: 2015-10-28 下午5:44:49
     */
    public static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = str.charAt(i);
            if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }

    /**
     * 中文参数转码
     *
     * @description: @param str
     * @description: @return
     * @author: caixuemei
     * @date: 2015-10-28 下午5:44:49
     */
    public static String string2Unicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            // 取出每一个字符
            char c = string.charAt(i);
            // 转换为unicode
            unicode.append("\\u" + Integer.toHexString(c));
        }
        return unicode.toString();
    }

    /**
     * 中文参数转码
     *
     * @description: @param str
     * @description: @return
     * @author: caixuemei
     * @date: 2015-10-28 下午5:44:49
     */
    public static String chinese2Unicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            char chr1 = str.charAt(i);
            if (isChinese2(chr1)) {// 汉字范围 \u4e00-\u9fa5 (中文)
                if (chr1 <= 256) {
                    result += "\\u00" + Integer.toHexString(chr1);
                } else if (chr1 <= 4095) {
                    result += "\\u0" + Integer.toHexString(chr1);
                } else {
                    result += "\\u" + Integer.toHexString(chr1);
                }
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    private static boolean isChinese2(char c) {
        try {
            StringBuffer buffer = new StringBuffer();
            buffer.append(c);

            if (buffer.toString().getBytes("utf-8").length != 1) {
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || c == '·';
    }

    /**
     * 获取系统当前年月日
     */
    public static String getSystemTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * 影藏身份证号码中间位数
     *
     * @param str
     * @return
     */
    public static String getIDCard(String str) {
        if (StringUtils.isEmpty(str) || str.length() < 9) {
            return "--";
        } else {
            StringBuffer string = new StringBuffer();
            for (int i = 2; i < str.length() - 5; i++) {
                string.append("*");
            }
            return str.substring(0, 2) + string + str.substring(str.length() - 5, str.length());
        }
    }

    /**
     * 影藏用户名字的名
     *
     * @param str
     * @return
     */
    public static String getUName(String str) {
        if (StringUtils.isEmpty(str)) {
            return "--";
        } else {
            return str.substring(0, 1) + "***";
        }
    }

    /**
     * 影藏用户名字的名
     *
     * @param str
     * @return
     */
    public static String getUName1(String str) {
        if (StringUtils.isEmpty(str)) {
            return "--";
        } else {
            if (str.length() > 1) {
                return "**" + str.substring(1, str.length());
            } else {
                return "**" + str.substring(0);
            }
        }
    }

    /**
     * 影藏手机号码中间的位数
     *
     * @param str
     * @return
     */
    public static String getPhone(String str) {
        if (StringUtils.isEmpty(str) || str.length() < 11) {
            return "--";
        } else {
            StringBuffer string = new StringBuffer();
            for (int i = 3; i < str.length() - 4; i++) {
                string.append("*");
            }
            return str.substring(0, 3) + string + str.substring(str.length() - 4, str.length());
        }
    }

    /**
     * @param p_url
     * @param params
     * @return
     * @description: 添加打印url地址的信息
     * @author: baibai
     * @date: 2015-8-25 上午11:11:41
     */
    public static String formatUrl(String p_url, Map<String, String> params) {
        StringBuilder url = new StringBuilder(p_url);
        if (url.indexOf("?") < 0)
            url.append('?');

        for (String name : params.keySet()) {
            url.append('&');
            url.append(name);
            url.append('=');
            url.append(params.get(name));
        }
        return url.toString().replace("?&", "?");
    }


}